#include<math.h>
#include<pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>

#include "Constant.h"
#include "ManageRoute.h"

int routerTable[256];

pthread_mutex_t router_mutex;

void ManageRoute_init()
{
	printf("ManageRoute_init\n");
	pthread_mutex_init(&router_mutex, NULL);

/*
	//----------------------gate way--------------------------------
	system("iptables -F");
	system("iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE");
	system("echo 1 >> /proc/sys/net/ipv4/ip_forward");
	routerTable[255]=255; //indicate internet addr
	routerEtx[255]=10;
	routerTTL[255]=1000000;
	//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
*/

}

//--------------------------------del or add OS's routeTable--------------------------
void del_router(int dst)
{
	//printf("del_router\n");
	if(dst == 255)
	{
		while(system("route del default") == 0);
		return;
	}

	pthread_mutex_lock(&router_mutex);
	if(routerTable[dst] != 0)
	{
		char cmd[50], *p = cmd;
		int i;
		bzero(cmd, sizeof(cmd));
		strcpy(cmd, "route del ");
		sprintf(cmd, "route del %s", HOSTIP);
		
		for(i=0;i<3;i++)
			p = strchr(p+1, '.');
		sprintf(p+1, "%d", dst);
		printf("%s\n", cmd);

		system(cmd);

		routerTable[dst] = 0;
	}
	pthread_mutex_unlock(&router_mutex);
}

void add_router(int dst, int gw)
{
	//printf("add_route dst=%d gw=%d\n", dst, gw);
	pthread_mutex_lock(&router_mutex);
	if(routerTable[dst] == gw)
	{
		pthread_mutex_unlock(&router_mutex);
		return;
	}

	del_router(dst);
	//printf("after del_router\n");

	//printf("1\n");
	char cmd[50];
	bzero(cmd, sizeof(cmd));
	int i, j, len;
	char *p = cmd;
	//printf("2\n");
	if(dst == 255)
		strcpy(cmd, "route add default gw ");
	else
	{
		sprintf(cmd, "route add %s", HOSTIP);
		for(i=0;i<3;++i)
			p = strchr(p+1, '.');
		sprintf(p+1,"%d gw ",dst);
	}

	p = cmd + strlen(cmd);
	sprintf(cmd + strlen(cmd), "%s", HOSTIP);
	
	for(i=0;i<3;++i)
		p = strchr(p+1, '.');
	sprintf(p+1,"%d",gw);

	printf("%s\n",cmd);
	system(cmd);

	routerTable[dst] = gw;
	pthread_mutex_unlock( &router_mutex);
	//printf("5\n");
}

int get_gw(int dst)
{
	return routerTable[dst];
}
